import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class GuessNumberGame extends JFrame implements ActionListener {
    private JTextField textField;
    private JButton buttonNew;
    private JButton buttonGuess;
    private JLabel labelResult;
    private int numberToGuess;

    public GuessNumberGame() {
        super("Guess Number Game");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // create components
        textField = new JTextField(10);
        buttonNew = new JButton("New number");
        buttonGuess = new JButton("Guess");
        labelResult = new JLabel("Guess a number between 1 and 100");

        // add components to frame
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(10, 10, 10, 10);
        panel.add(textField, c);
        c.gridx = 1;
        panel.add(buttonGuess, c);
        c.gridx = 0;
        c.gridy = 1;
        panel.add(buttonNew, c);
        c.gridwidth = 2;
        c.gridy = 2;
        panel.add(labelResult, c);
        add(panel);

        // add action listeners to buttons
        buttonNew.addActionListener(this);
        buttonGuess.addActionListener(this);

        // show the frame
        setVisible(true);
    }

    // generate a new random number between 1 and 100
    private void generateNumberToGuess() {
        Random rand = new Random();
        numberToGuess = rand.nextInt(100) + 1;
    }

    // process user's guess
    private void processGuess() {
        try {
            int guess = Integer.parseInt(textField.getText());
            if (guess < 1 || guess > 100) {
                labelResult.setText("Invalid guess");
            } else if (guess == numberToGuess) {
                labelResult.setText("You win!");
            } else if (guess < numberToGuess) {
                labelResult.setText("Too low");
            } else {
                labelResult.setText("Too high");
            }
        } catch (NumberFormatException ex) {
            labelResult.setText("Invalid guess");
        }
    }

    // handle button clicks
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == buttonNew) {
            generateNumberToGuess();
            labelResult.setText("Guess a number between 1 and 100");
        } else if (e.getSource() == buttonGuess) {
            processGuess();
        }
    }

    public static void main(String[] args) {
        new GuessNumberGame();
    }
}
